/**
 * Free software.
 */

package org.nanhill.commons.servlet.filter;

import static org.nanhill.commons.http.HttpHeader.ACCEPT_LANGUAGE;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.nanhill.commons.http.HttpHeader;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-10-15
 */
public class I18nCharacterEncodingFilter extends CharacterEncodingFilter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (forceEncoding) {
			request.setCharacterEncoding(this.encoding);
		} else if (request.getCharacterEncoding() == null) {
			if (request instanceof HttpServletRequest) {
				HttpServletRequest httpRequest = (HttpServletRequest) request;
				String acceptLanguage = httpRequest.getHeader(ACCEPT_LANGUAGE);
				acceptLanguage = HttpHeader.getDefaultCharSet(acceptLanguage);
				request.setCharacterEncoding(acceptLanguage);
			}
		}
		// Pass control on to the next filter
		chain.doFilter(request, response);
	}

}
